# code:utf8
import json
import logging
import math
from datetime import datetime
from scrapy.utils.project import get_project_settings
from scrapy.exceptions import IgnoreRequest
from abchina.util.aes_util import AesCrypter
from zc_core.model.items import *
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_number, parse_timestamp
from abchina.matcher import match_saled, match_order_time
from zc_core.util.encrypt_util import build_sha1_order_id, md5
from zc_core.util.order_deadline_filter import OrderItemFilter
from zc_core.util.sku_id_parser import convert_id2code

logger = logging.getLogger('rule')
order_filter = OrderItemFilter()
settings = get_project_settings()
suppliers = settings.get('SUPPLIERS', {})


def decrypt(response):
    """
    响应对象解密
    :param response:
    :return:
    """
    rs = json.loads(response.text)
    meta = response.meta
    url = response.url
    if rs and meta and 'sec_key' in meta and 'sec_iv' in meta \
            and meta.get('sec_key') and meta.get('sec_iv'):
        if 'Value' in rs:
            enc_msg = rs.get('Value')
            aes = AesCrypter(meta.get('sec_key'), meta.get('sec_iv'))
            return aes.decrypt(enc_msg)
    else:
        raise IgnoreRequest('解密异常：<url=%s, meta=%s>' % (url, meta))


# 解析首页root catalog列表
def parse_root_catalog(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    cats = list()
    rs = json.loads(decrypt(response))
    for cat1_json in rs.get('List'):
        # 一级分类
        cat_id = str(cat1_json.get('CatgId'))
        cat_name = cat1_json.get('CatgName')
        cat = _build_catalog(cat_id, cat_name, '', 1, batch_no)
        cats.append(cat)

    return cats


# 解析首页sub catalog列表
def parse_sub_catalog(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    cats = list()
    rs = json.loads(decrypt(response))
    for cat2_json in rs:
        # 二级分类
        cat2_id = str(cat2_json.get('CatgId'))
        cat2_name = cat2_json.get('CatgName')
        cat2 = _build_catalog(cat2_id, cat2_name, meta.get('parentId'), 2, batch_no)
        cats.append(cat2)
        # 三级分类
        for cat3_json in cat2_json.get('Child'):
            cat3_id = str(cat3_json.get('CatgId'))
            cat3_name = cat3_json.get('CatgName')
            cat3 = _build_catalog(cat3_id, cat3_name, cat2_id, 3, batch_no)
            cats.append(cat3)

    return cats


def _build_catalog(cat_id, cat_name, parent_id, level, batch_no):
    cat = Catalog()
    cat['catalogId'] = str(cat_id)
    cat['catalogName'] = cat_name
    cat['parentId'] = str(parent_id)
    cat['level'] = level
    if cat['level'] == 3:
        # 1、是
        cat['leafFlag'] = 1
    else:
        # 2、否
        cat['leafFlag'] = 2
    cat['linkable'] = 1
    cat['batchNo'] = batch_no

    return cat


# 解析sku列表
def parse_total_page(response):
    meta = response.meta
    page_size = meta.get('pageSize', 50)
    rs = json.loads(decrypt(response))
    if rs and rs.get('TotalRows', 0):
        return math.ceil(rs.get('TotalRows', 0) / page_size)

    return 0


# 解析前台sku列表
def parse_sku_front(response):
    meta = response.meta
    batch_no = meta.get('batchNo')

    sku_list = list()
    rs = json.loads(decrypt(response))
    if rs and len(rs.get('List', [])):
        for row in rs.get('List'):
            supplier_name = suppliers.get(row.get('SourceId'), '')
            sku = Sku()
            sku['batchNo'] = batch_no
            sku['skuId'] = str(row.get('ProductUnityCode'))
            sku['supplierName'] = supplier_name
            # sku['unit'] = row.get('SaleUnit', '')
            sku['catalog3Id'] = str(row.get('Category'))
            # sku['catalog3Name'] = row.get('CategoryName', '')
            sku['brandName'] = row.get('Brand', '')
            sku['brandModel'] = row.get('PrdModel', '')
            sku['soldCount'] = row.get('SalesVolumn', '')
            sku['salePrice'] = row.get('UnitPrice', -99)
            sku['skuImg'] = row.get('PrimaryImage')
            sku['supplierSkuId'] = row.get('ProductEXCode', '')
            sku['supplierName'] = supplier_name
            sku_list.append(sku)

    return sku_list


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')

    sku_list = list()
    rs = json.loads(decrypt(response))
    if rs and len(rs.get('List', [])):
        for row in rs.get('List'):
            sp_id = row.get('SourceId')
            supplier_name = suppliers.get(sp_id, '')
            sku = Sku()
            sku['batchNo'] = batch_no
            sku['skuId'] = str(row.get('ProductUnityCode'))
            sku['catalog3Id'] = str(row.get('Category'))
            sku['catalog3Name'] = row.get('CategoryName', '')
            # sku['brandName'] = row.get('Brand', '')
            # sku['soldCount'] = row.get('SalesVolumn', '')
            sku['brandModel'] = row.get('PrdModel', '')
            sku['salePrice'] = row.get('UnitPrice', -99)
            sku['skuImg'] = row.get('PrimaryImage')
            sku['supplierSkuId'] = row.get('ProductEXCode', '')
            if sp_id:
                sku['supplierId'] = sp_id
            if supplier_name:
                sku['supplierName'] = supplier_name
            else:
                sku['supplierName'] = row.get('MerchantName', '')
            sku['unit'] = row.get('SaleUnit', '')
            sku['saleStatus'] = row.get('State')
            sku_list.append(sku)

    return sku_list


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    catalog3_id = meta.get('catalog3Id')
    catalog3_name = meta.get('catalog3Name', '')
    sku_img_id = meta.get('skuImg')

    data = json.loads(decrypt(response))
    if data:
        sale_price = parse_number(data.get('UnitPrice'))
        mk_price = parse_number(data.get('MktPrice'))
        brand = data.get('Brand')
        state = data.get('State', 1)
        # 下架
        if sale_price > 0 and mk_price > 0:
            result = ItemData()
            # -------------------------------------------------
            result['batchNo'] = batch_no
            result['skuId'] = sku_id
            result['skuName'] = data.get('ProductName')
            result['skuImg'] = 'https://e.abchina.com/qyjc/site/GenProduct/ProductImage?imageId={}&format='.format(sku_img_id)
            result['catalog1Id'] = ''
            result['catalog1Name'] = ''
            result['catalog2Id'] = ''
            result['catalog2Name'] = ''
            result['catalog3Id'] = str(catalog3_id)
            result['catalog3Name'] = catalog3_name
            result['salePrice'] = sale_price
            result['originPrice'] = mk_price

            tp = match_saled(data.get('SaledNo'))
            if tp and len(tp) == 2:
                result['unit'] = tp[1]
                result['soldCount'] = parse_number(tp[0])
            else:
                result['unit'] = ''
                result['soldCount'] = 0
            if brand:
                result['brandId'] = md5(brand)
                result['brandName'] = brand
            sp_id = data.get('SourceId')
            result['supplierId'] = sp_id
            result['supplierName'] = data.get('SourceName')
            sp_sku_id = data.get('ProductEXCode')
            result['supplierSkuId'] = sp_sku_id
            sp_sku_code = sp_sku_id
            # 供应商商品链接
            if sp_id == 'JD1001':
                result['supplierSkuLink'] = 'https://item.jd.com/{}.html'.format(sp_sku_id)
            elif sp_id == 'SN1002':
                result['supplierSkuLink'] = 'https://product.suning.com/0000000000/{}.html'.format(sp_sku_id)
            elif sp_id == 'DL1003':
                sp_sku_code = convert_id2code('deli', sp_sku_id)
                result['supplierSkuLink'] = 'https://b2b.nbdeli.com/Goods/ItemDetail_{}_40.htm'.format(sp_sku_code)
            result['supplierSkuCode'] = sp_sku_code
            result['brandModel'] = data.get('PrdModel')
            result['genTime'] = datetime.utcnow()
            # -------------------------------------------------

            return result


# 解析order列表
def parse_order_item(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    supplier_name = meta.get('supplierName')

    orders = list()
    rs = json.loads(decrypt(response))
    if rs and len(rs.get('List')):
        prev_order = None
        same_order_no = 1
        for idx, row in enumerate(rs.get('List')):
            # 采购时间  2018-12-14 11:18
            order_timestamp = match_order_time(row.get('TradeTime'))
            order_time = parse_timestamp(int(str(order_timestamp)[:-3]))
            if order_filter.to_save(order_time):
                order = OrderItem()
                order['skuId'] = sku_id
                order['amount'] = row.get('ProductCount')
                order['totalPrice'] = row.get('TotalPrice')
                order['userId'] = row.get('BranchId')
                order['orderDept'] = row.get('BranchName')
                order['supplierName'] = supplier_name
                order['orderTime'] = order_time
                order['batchNo'] = time_to_batch_no(order_time)
                order['genTime'] = datetime.utcnow()
                if prev_order and prev_order.equals(order):
                    same_order_no = same_order_no + 1
                else:
                    same_order_no = 1
                addition = {
                    'sameOrderNo': same_order_no,
                    'orderTimeStr': order_timestamp,
                }
                sha1_id = build_sha1_order_id(order, addition)
                order['id'] = sha1_id
                order['orderId'] = sha1_id
                orders.append(order)
                prev_order = order
    else:
        logger.info('无单[%s]', sku_id)

    return orders


if __name__ == '__main__':
    # 采购时间  2018-12-14 11:18
    order_timestamp = match_order_time('/Date(1531298188000)/')
    order_time = datetime.fromtimestamp(int(str(order_timestamp)[:-3]))
    print(order_time)
